package com.chinasoft.back.service.impl;

import com.chinasoft.back.mapper.UserMapper;
import com.chinasoft.back.pojo.Result;
import com.chinasoft.back.pojo.User;
import com.chinasoft.back.service.UserService;
import com.chinasoft.back.utils.JwtUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

/**
 * @author 中软zhang
 * @create 2023-08-28 14:10
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public Result<String> login(User user) {
        // 查询数据库
        User db = userMapper.selectByName(user.getUsername());
        // 返回对象
        Result<String> ret = new Result<>();
        // 判断 密码是否对
        if (db != null) {
            String md5 = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
            System.out.println(md5);
            // 登录成功
            ret.setStatus(0);
            ret.setMessage("你登录成功！");
            // 获取 token
            String token = JwtUtils.createToken("" + db.getId(), db.getUsername());
            ret.setToken(token);
            System.out.println(ret);
            return ret;
        } else {
            ret.setStatus(1);
            ret.setMessage("身份认证失败！");
            System.out.println(ret);
            // 登录失败
            return ret;
        }
    }

    @Override
    public User queryByName(String userName) {
        return userMapper.selectByName(userName);
    }

    @Override
    public List<User> queryByPage(int pageNum, int pageSize) {
        // 完成分页
        PageHelper.startPage(pageNum, pageSize);
        List<User> users = userMapper.selectAll();
        // 获取 总记录数
        PageInfo<User> info = new PageInfo<>(users);
        System.out.println(info.getTotal());

        return users;
    }
}
